package com.java8.demo.stream;

import com.java8.demo.model.Person;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamDemo {

    public static void main(String[] args) {
        //初始化数据
        List<Person> personList = new ArrayList<Person>() {{
            add(new Person() {{
                setName("小明");
                setAge(18);
                setStudent(true);

            }});
            add(new Person() {{
                setName("小乔");
                setAge(16);
                setStudent(false);
            }});
        }};


        //获取流 -- 集合
        Stream<Person> streamList = personList.stream();
        streamList.forEach(person -> System.out.println(person.getName()));

        //获取流 -- 数组
        String[] names = {"小明", "皮特", "沃尔特"};
        Stream<String> streamArray = Arrays.stream(names);
        streamArray.forEach(s -> System.out.println(s));

        //获取流 -- 直接将几个值变成流对象
        Stream<String> stream = Stream.of("瓦特", "小乔", "小文");
        stream.forEach(s -> System.out.println(s));

        //获取流 -- 文件
        try (Stream lines = Files.lines(Paths.get("D:\\JAVAPorject\\java8-demo\\stream\\src\\main\\resources\\file.txt"), Charset.defaultCharset())) {
            //可对lines做一些操作
            Iterator iterator = lines.iterator();
            while (iterator.hasNext()) {
                Object next = iterator.next();
                System.out.println(next);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


        //筛选filter
        List<Person> result = personList.stream()
                .filter(Person::getStudent)
                .collect(Collectors.toList());
        result.forEach(person -> System.out.println("学生：" + person.getName()));
    }

}
